<?php
namespace App\Http\Controllers\Api\Zghpt;

use App\Fishing;
use App\GameZghpt;
use App\GameZghptHongbao;
use App\GameZghptUserCrownHb;
use App\Http\Controllers\Controller;
use App\Models\Cq\CqRecordLog;
use App\Models\Sgdzz\PayLog as SgdzzPaylog;
use App\User;
use App\UserCoinLog;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class HbController extends Controller 
{
	const bussiness_id = 1;  //中国好跑团的bussiness_id

	const min_score = 10;
	const max_score = 30;

	const min_coin = 1;
	const max_coin = 30;  //随机红包1分到3毛
	const min_coin_third = 100;
	const max_coin_third = 200;

	const crown_user_count = 5;

	const next_time_per = 3600;  //vip的抢红包倒计时的设置，测试调到10秒， 正式要调回3600
	const next_time_per_not_vip = 10800; //非vip的抢红包等待时间

	const user_today_count = 6; //用户一天抢红包的限制数

	const fans_play_user_count_get_reward = 6; //粉丝有6个人玩游戏

	protected $wechat;

	public function __construct()
    {
        $this->wechat = app('wechat');
    }

	public function index()
	{
		$user = auth()->user();
		$gameZghpt = $user->game_zghpt;
		
		$fans = User::where('finder_id', $user->id)->get();

		$add_time = self::next_time_per_not_vip;
		$status = 0;
		if ( $gameZghpt->level ) {
			$status = 1;
			$add_time = self::next_time_per;
		}

		$cur_time = time();
		$fans_crown_count = 0;
		foreach ($fans as $key => $fan) {
			if ( $fan->game_zghpt && $fan->game_zghpt->level > 0 ) {
				$fans_crown_count++;
			}
		}

		$crown_user_count = self::crown_user_count;

		$lasthb = GameZghptHongbao::where('uid', $user->id)->where('status', $status)->where('from_uid', $user->id)->orderBy('id', 'desc')->select('created_at')->first();

		$has_crown_count = $fans_crown_count%$crown_user_count;
		$crown_hb_can_get = 0;

		if ( $fans_crown_count >= $crown_user_count ) {
			$crown_level = floor( $fans_crown_count/$crown_user_count );
			$unlockCount = GameZghptUserCrownHb::where('user_id', $user->id)->count();
			// $userCrownHb = GameZghptUserCrownHb::where('user_id', $user->id)->where('crown', $crown_level )->first();
			if ( $unlockCount < $crown_level ) {
				$crown_hb_can_get = 1;
				$has_crown_count = $has_crown_count ?: $crown_user_count;
			}
		}
		
		$total = UserCoinLog::totalXyb( $user->id );
        $XYB = $total < 0 ? 0 : $total  ;

		$data['user'] = $user->toArray();
		$data['user']['XYB'] = $XYB;
		$data['user']['JB'] = UserCoinLog::totalJb( $user->id );
		$data['user']['fans_crown_count'] = $fans_crown_count;
		$data['user']['need_unlock_count'] = $crown_user_count - $has_crown_count;
		$data['user']['unlock_count'] = GameZghptUserCrownHb::where('user_id', $user->id)->count();
		$data['user']['next_second'] = $lasthb ? (strtotime($lasthb->created_at) + $add_time - $cur_time) : 0 ;
		$data['user']['level'] = $gameZghpt->level;
		$data['user']['crown_hb_percent'] = ( $has_crown_count/$crown_user_count ) * 100;
		$data['user']['crown_hb_can_get'] = $crown_hb_can_get;
		$data['user']['count'] = $crown_user_count;

		return response()->json(['code' => 1000, 'data' => $data]);
	}

	public function create( Request $request )
	{
		$from_user = $request->input('from_user');
		$cur_time = time();

		$user = auth()->user();
		$level  = $user->game_zghpt->level;
		$status = $level > 0 ? 1 : 0; //改回用户自己的状态

		$from_user_obj = User::findOrFail( $from_user );
		if ( !$from_user_obj->game_zghpt ) {
			$gameZghpt = new GameZghpt();
            $gameZghpt->user_id = $from_user;
            $gameZghpt->quota = 0;
            $gameZghpt->level = 0;
            $gameZghpt->save();
		}
        $from_user_obj = User::findOrFail( $from_user );
		
		if ( $from_user != $user->id && $from_user_obj->finder_id != $user->id ) {
			return response()->json([]);
		}

		$user_today_count = GameZghptHongbao::where('uid', $user->id)->where('from_uid', $from_user)->where('date', date('Y-m-d'))->count();
		
		if ( $user_today_count >= self::user_today_count ) {
			return response()->json(['code' => 1004, 'msg' => '今天的次数已用完']);
		}

	 	$lasthb = GameZghptHongbao::where('uid', $user->id)->where('from_uid', $from_user)->orderBy('id', 'desc')->first();

	 	$next_time = self::next_time_per_not_vip;
	 	if ( $from_user_obj->game_zghpt->level ) {
	 		$next_time = self::next_time_per;
	 	}

	 	$surplus_time = 0;
		if ( $lasthb ) {
			$surplus_time = strtotime($lasthb->created_at) + $next_time - $cur_time ;
		}

		$data['surplus_time'] = $surplus_time;

		if ( $surplus_time > 0 ) {
			return response()->json(['code' => 1001, 'msg' => '时间还没到', 'data' => $data]);
		}

		$quota = $user->game_zghpt->quota ;
		$user_geted_moneys = GameZghptHongbao::where('uid', $user->id)->where('status', $status)->sum('money');

		//送积分
		$score = rand( self::min_score, self::max_score );
		
		//对方非vip可抢1分钱
		if ( $from_user_obj->game_zghpt->level < 1 ) {
		    //每天抢非VIP超过50次，不让再抢了
		    if(GameZghptHongbao::where('uid', $user->id)->where('status', $status)->where('money', 0.01)->where('created_at', '>=', Carbon::today()->startOfDay())->count() < 50){
                $money = 0.01;
            } else {
		        $money=0;
            }
//			$status = 1;
		} else {
			//配额为0也能抢1分钱
			$money = 0;
			if ( $user_geted_moneys < $quota ) {
				$left_quota = $quota - $user_geted_moneys;

				//前三个红包是1 - 2
				$hb_count = GameZghptHongbao::where('uid', $user->id)->count();
				$max_coin = $hb_count <= 3 ? self::max_coin_third : self::max_coin;
				$min_coin = $hb_count <= 3 ? self::min_coin_third : self::min_coin;

				$max = $left_quota > ($max_coin/100) ? $max_coin : ($left_quota*100);

				$money = rand( $min_coin, $max ) / 100;
			} else {
				$money = 0.01;
//				$status = 1;
			}
		}

		$hongbao = new GameZghptHongbao();
		$hongbao->uid = $user->id;
		$hongbao->from_uid = $from_user;
		$hongbao->hb_key = date('YmdH') . '-' . $user->id . '-' . $from_user . '-' . $status;
		$hongbao->date = date('Y-m-d');
		$hongbao->money = $money;
		$hongbao->status = $status;
		$hongbao->save();

		$this->alarm( $user->id, $level );

		$key = '1-'. $user->id . '-'. $score .'-' . $cur_time . '-5';
		UserCoinLog::log( self::bussiness_id, $user->id, UserCoinLog::TYPE_JB, $score, '抢到积分', $key );

		if ( $level > 0 ) {

			$key = '1-'. $user->id . '-'. $money .'-' . $cur_time . '-6';
			UserCoinLog::log( self::bussiness_id, $user->id, UserCoinLog::TYPE_XYB, $money, '抢到用户红包', $key );
			// $user->XYB += $money;
			// $user->JB += $score;
			// $user->save();
		} else {
			$money = rand( 100, 200 )/100;
			try {
				$this->wechat->staff->message('您好，您错过了'. $money .'小妖币的红包，请<a href="http://ga.cloudxt.cn/zghpt/vip/page">立即升级VIP</a>！')->to($user->openid)->send();
			} catch (\Exception $e) {
			}
		}

		$data['score'] = $score;
		$data['money'] = $money;
		$data['status'] = $status;
		$data['surplus_time'] = $next_time;
		return response()->json(['code' => 1000, 'data' => $data]);
	}

	//解锁
	public function unlock()
	{
		$user = auth()->user();
		$game_zghpt = $user->game_zghpt;

		$count = 0;
		foreach (User::where('finder_id', $user->id)->get() as $fan) {
			if ( $fan->game_zghpt && $fan->game_zghpt->level > 0 ) {
				$count++;
			}
		}

		$crown_user_count = self::crown_user_count;
		
		if ( $count < $crown_user_count ) {
			return response()->json(['code' => 2000, 'msg' => '粉丝还不够']);
		}

		$unlockCount = GameZghptUserCrownHb::where('user_id', $user->id)->count();
		$userCanGetCount = floor( $count/$crown_user_count );

		if ( $unlockCount >= $userCanGetCount ) {
			return response()->json(['code' => 2001, 'msg' => '红包已领取']);
		}

		//解锁成功的金额
		$money = 100;
		$status = 0;
		if ( $game_zghpt->level > 0 ) {
			try {
            	DB::beginTransaction();

				$status = 1;
				$userCrownHb = new GameZghptUserCrownHb();
				$userCrownHb->user_id = $user->id;
				$userCrownHb->crown = $unlockCount+1;
				$userCrownHb->save();
				
				$unlockCount = GameZghptUserCrownHb::where('user_id', $user->id)->count();
				if ( $unlockCount > $userCanGetCount ) {
					DB::rollBack();
					return ;
				}

				// $user->XYB += $money;
				// $user->save();
				$cur_time = time();
				$key = '1-'. $user->id . '-'. $money .'-' . $cur_time . '-7';
				UserCoinLog::log( self::bussiness_id, $user->id, UserCoinLog::TYPE_XYB, $money, '解锁累计粉丝红包', $key );
				DB::commit();
			} catch (\Exception $e) {
				DB::rollBack();
				$status = 0;
			}
		} else {
			try {
				$this->wechat->staff->message('您好，您错过了'. $money .'元钱的粉丝解锁红包，请<a href="http://ga.cloudxt.cn/zghpt/vip/page">立即升级VIP</a>！')->to($user->openid)->send();
			} catch (\Exception $e) {
			}
		}

		$data['money'] = $money;
		$data['status'] = $status;
		$data['count'] = $crown_user_count;

		return response()->json(['code' => 1000, 'msg' => '领取成功', 'data' => $data]);
	}

	public function fans()
	{
		$user = auth()->user();
		$user_level  = $user->game_zghpt->level;

		$cur_time = time();
		
		$fans = User::where('finder_id', $user->id)->orWhere('id', $user->id)->paginate(10);
		foreach ($fans as $key => $fan) {
			$add_time = self::next_time_per_not_vip;
			$level = 0;
			if ( $fan->game_zghpt && $fan->game_zghpt->level ) {
				$add_time = self::next_time_per;
				$level = $fan->game_zghpt->level;
			}

			$lasthb = GameZghptHongbao::where('uid', $user->id)->where('from_uid', $fan->id)->orderBy('id', 'desc')->select('created_at')->first();

			$surplus_time = $lasthb ? strtotime($lasthb->created_at) + $add_time - $cur_time : 0;

			$fan->level = $level;
			$fan->next_second = $surplus_time;
		}

		return response()->json(['code' => 1000, 'data' => $fans]);
	}

	//警报
	private function alarm( $user_id, $level )
    {
//        if ($level < 1) {
        $total = GameZghptHongbao::where('uid', $user_id)->where('status', 1)->where('created_at', '>=', Carbon::today()->startOfDay())->where('created_at', '<=', Carbon::today()->endOfDay())->sum('money');

        $fans = User::where('finder_id', $user_id)->get();
        $fans_vip_count = 0;
        foreach ($fans as $key => $fan) {
            if($gameZghpt = $fan->game_zghpt) {
                if ($gameZghpt->level > 0) {
                    $fans_vip_count++;
                }
            }
        }

        if ($fans_vip_count == 0 && $total > 10) {
            //发出警报
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "http://sms-api.luosimao.com/v1/send_batch.json");
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 8);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_USERPWD, 'api:key-5145112f10b704bbd5592f80402c77b5');
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, array('mobile_list' => '13726873311,18676571127', 'message' => '你好，发现异常情况。项目：中国好炮团，UID：' . $user_id . '，描述：用户抢红包超过十元且下级无VIP用户。【小妖传媒】'));
            $res = curl_exec($ch);
        }
//        }
    }

    //获取粉丝奖励
    public function gameReward()
    {
    	$user = auth()->user();
    	
    	$played_today_count = 0;
    	$self_played = 0;

    	$today_start = date( 'Y-m-d' );
    	$today_end   = date( 'Y-m-d', strtotime( '+1 day' ) );
    	
    	//自己是否有钓鱼
    	$self_fish_count = Fishing::where('mid', $user->id)->where('created_at', '>=', $today_start )->where('created_at', '<', $today_end)->count();
    	//水果大作战
    	$self_sgdzz_count = SgdzzPaylog::where('user_id', $user->id)->where('created_at', '>=', $today_start )->where('created_at', '<', $today_end)->count();
    	//猜拳
    	$self_cq_count = CqRecordLog::where('user_id', $user->id)->where('created_time', '>=', $today_start )->where('created_time', '<', $today_end)->count();

    	//自己今天有玩游戏
    	if ( $self_fish_count > 0 || 
    		 $self_sgdzz_count > 0 || 
    		 $self_cq_count > 0 ) {

    		$self_played = 1;

    		//粉丝是否有5个人玩
    		$fans_uids = User::where('finder_id', $user->id)->select('id')->get();

    		//钓鱼
    		$fans_fishing = Fishing::whereIn('mid', $fans_uids)->where('created_at', '>=', $today_start )->where('created_at', '<', $today_end)->select('mid as user_id')->distinct()->get()->toArray();

    		//水果大作战
    		$fans_sgdzz = SgdzzPaylog::whereIn('user_id', $fans_uids)->where('created_at', '>=', $today_start )->where('created_at', '<', $today_end)->select('user_id')->distinct()->get()->toArray();
    		//猜拳
    		$fans_cq = CqRecordLog::whereIn('user_id', $fans_uids)->where('created_time', '>=', $today_start )->where('created_time', '<', $today_end)->select('user_id')->distinct()->get()->toArray();

    		$fans_fishing_uids = array_column( $fans_fishing, 'user_id' );
    		$fans_sgdzz_uids = array_column( $fans_sgdzz, 'user_id' );
    		$fans_cq_uids = array_column( $fans_cq, 'user_id' );

    		$fans_played_user_count = count( array_unique( array_merge( $fans_fishing_uids, $fans_sgdzz_uids, $fans_cq_uids ) ) );

    		if ( $fans_played_user_count < self::fans_play_user_count_get_reward ) {
    			return response()->json(
    				[ 	
    					'code' => 1001, 
    					'msg' => '粉丝不够' . self::fans_play_user_count_get_reward . '人玩，拉多几个人来玩吧',
    					'count' => $fans_played_user_count
    				]
    			);
    		}

    		//粉丝多于x个人玩游戏可获得当天红包
    		$xyb = rand(600, 650) / 100;
    		$key = self::bussiness_id . '-' . $user->id . '-' . $xyb . '-' . date('Ymd') . '-10';
    		UserCoinLog::log( self::bussiness_id, $user->id, UserCoinLog::TYPE_XYB, $xyb, '粉丝每日玩游戏奖励', $key );

    		return response()->json(['code' => 1000, 'msg' => '领取成功']);
    	}

    	return response()->json(['code' => 1002, 'msg' => '您今天没玩游戏']);
    }
}